package com.yunfeng.supercall.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore.MediaColumns;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.ly.quickdev.library.adapter.ListBaseAdapter;
import com.ly.quickdev.library.bean.Constants;
import com.ly.quickdev.library.manager.SelectPhotoManager;
import com.ly.quickdev.library.utils.ImageTools;
import com.ly.quickdev.library.utils.ImageTools.OnBitmapCreateListener;
import com.ly.quickdev.library.view.SquareImageView;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.app.AppContext;
import com.yunfeng.supercall.httputils.MyAjaxCallBack;
import com.yunfeng.supercall.httputils.UploadUtilsAsyncTask.OnUplaodListener;

/**
 * 我要分享
 * 
 * @author 洋
 * 
 */
public class ShareActivity extends BaseActivity implements OnItemClickListener,
		OnUplaodListener {

	private GridView mGridView;
	private EditText mEditText;
	private SelectPhotoManager mPhotoManager;
	private List<String> mPaths;
	private GridAdapter mAdapter;
	private int mIndex;
	private ImageTools mImageTools;
	private FrameLayout mFrameLayoutBack;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_i_want_share);
		mFrameLayoutPublish = (FrameLayout) findViewById(R.id.framelayout_publish);
		
		
		mImageViewBack = (ImageView) findViewById(R.id.imageview_back);
		mImageViewBack.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		
		mFrameLayoutBack = (FrameLayout) findViewById(R.id.framelayout_back);
		mFrameLayoutBack.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		
		mPaths = new ArrayList<String>();
		mEditText = findView(R.id.et);
		mGridView = findView(R.id.gridview);
		mAdapter = new GridAdapter(getActivity(), mPaths);
		mGridView.setAdapter(mAdapter);
		mPhotoManager = SelectPhotoManager.getInstance();
		mPhotoManager.setLimite(9);
		mStringBuilder = new StringBuilder();
		mGridView.setOnItemClickListener(this);
		
		mFrameLayoutPublish.setOnClickListener((android.view.View.OnClickListener) onClickListenr);
		mImageTools = new ImageTools(this);
		String mAction = getIntent().getAction();// 从系统分享列表里调用而来的action
		if (!TextUtils.isEmpty(mAction)) {
			if (Intent.ACTION_SEND.equals(mAction)) {
				mEditText
						.setText(getIntent().getStringExtra(Intent.EXTRA_TEXT));
				Uri mUri = getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
				if (mUri != null) {
					String path = getFilePathFromContentUri(mUri,
							getContentResolver());
					if (!TextUtils.isEmpty(path)) {
						mPaths.add(path);
						mAdapter.notifyDataSetChanged();
					}
				}
			} else if (Intent.ACTION_SEND_MULTIPLE.equals(mAction)) {
				List<Uri> mUris = getIntent().getParcelableArrayListExtra(
						Intent.EXTRA_STREAM);
				if (mUris != null) {
					add: for (int i = 0; i < mUris.size(); i++) {
						String path = getFilePathFromContentUri(mUris.get(i),
								getContentResolver());
						if (!TextUtils.isEmpty(path)) {
							mPaths.add(path);
							if (i == 7) {
								showToast(R.string.most_eight_photos);
								break add;
							}
						}
					}
					mAdapter.notifyDataSetChanged();
				}
			}
		}
		initFile();
	}

	
	android.view.View.OnClickListener onClick = new android.view.View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			finish();
		}
	}; 
	
	/**
	 * Gets the corresponding path to a file from the given content:// URI
	 * 
	 * @param selectedVideoUri
	 *            The content:// URI to find the file path from
	 * @param contentResolver
	 *            The content resolver to use to perform the query.
	 * @return the file path as a string
	 */
	public static String getFilePathFromContentUri(Uri selectedVideoUri,
			ContentResolver contentResolver) {
		String filePath;
		String[] filePathColumn = { MediaColumns.DATA };

		Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn,
				null, null, null);
		// 也可用下面的方法拿到cursor
		// Cursor cursor = this.context.managedQuery(selectedVideoUri,
		// filePathColumn, null, null, null);

		cursor.moveToFirst();

		int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
		filePath = cursor.getString(columnIndex);
		cursor.close();
		return filePath;
	}

	private void initFile() {
		File file = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/.printphoto/");
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		switch (v.getId()) {
		case R.id.right_text:
			if (getLoginManager(getActivity()).isLogined()) {
				String text = mEditText.getText().toString();
				if (mPaths != null && !mPaths.isEmpty()) {
					uploadImgs(mIndex);
				} else if (!TextUtils.isEmpty(text)) {
					submitShare("", text);
				}
			} else {
				startActivityForResult(
						new Intent(this, LoginActivity.class).putExtra(
								KEY_DATA, false), 800);
			}
			break;
		}
	}

	
	android.view.View.OnClickListener onClickListenr = new android.view.View.OnClickListener() {
		

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (getLoginManager(getActivity()).isLogined()) {
				String text = mEditText.getText().toString();
				if (mPaths != null && !mPaths.isEmpty()) {
					uploadImgs(mIndex);
				} else if (!TextUtils.isEmpty(text)) {
					submitShare("", text);
				}
			} else {
				startActivityForResult(
						new Intent(ShareActivity.this, LoginActivity.class).putExtra(
								KEY_DATA, false), 800);
			}	
		}
	};
	private StringBuilder mStringBuilder;
	private FrameLayout mFrameLayoutPublish;
	private ImageView mImageViewBack;

	private void submitShare(String imgs, String content) {
		JSONObject json = getBaseParams(getActivity());
		try {
			json.put("i_content", content);
			json.put("i_img", imgs);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHttpClient.post(FUNCTION_ADD_SHARE, json, new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub
				cancelProgressDialog();
				showToast(msg);
			}

			@Override
			public void onReceiveData(String data, String msg) {
				// TODO Auto-generated method stub
				cancelProgressDialog();
				showToast("分享成功");
				finish();
			}
		});
	}

	public void uploadImgs(int index) {
		if (index >= mPaths.size()) {
			showProgressDialog(R.string.publishing);
			submitShare(mStringBuilder.toString(), getTextViewText(R.id.et));
		}
		if (index < mPaths.size()) {
			mIndex = index;
			showProgressDialog(getString(R.string.uploading_photo_index,
					index + 1));
			mHttpClient.upLoadImg(mPaths.get(mIndex),
					System.currentTimeMillis() + ".jpg", this);
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view,
			final int position, long id) {
		// TODO Auto-generated method stub
		if (position < mAdapter.getCount() - 1 || mPaths.size() == 9) {
			Builder mBuilder = new Builder(this);
			mBuilder.setMessage(R.string.delete_this_photo);
			mBuilder.setTitle(R.string.notice);
			mBuilder.setNegativeButton(R.string.retain, null);
			mBuilder.setPositiveButton(R.string.delete,
					new Dialog.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							mPaths.remove(position);
							mAdapter.notifyDataSetChanged();
						}
					});
			mBuilder.show();
		} else {
			List<String> list = SelectPhotoManager.getInstance().getPhotos();
			if (list != null) {
				list.clear();
			}
			showChoose();
		}
	}

	private void showChoose() {
		Builder mBuilder = new Builder(this);
		mBuilder.setItems(R.array.select_choose_photo_mode,
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						if (which == 0) {
							mImageTools.openCamara();
						} else {
							mPhotoManager.setLimite(9 - mPaths.size());
							startActivityForResult(
									new Intent(ShareActivity.this,
											SuperChoosePhotoActivity.class)
											.setAction(Constants.ACTION_CHOOSE_PHOTO_MULTI),
									ImageTools.GALLERY);
						}
					}
				});
		mBuilder.setTitle(R.string.choose_photo);
		mBuilder.show();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case ImageTools.GALLERY:
				List<String> path = data.getStringArrayListExtra(KEY_DATA);
				// mPaths.clear();
				mPaths.addAll(path);
				mAdapter.notifyDataSetChanged();
				break;

			case ImageTools.CAMARA:
				mImageTools.getBitmapFromCamara(new OnBitmapCreateListener() {

					@Override
					public void onBitmapCreate(Bitmap bitmap, String path) {
						// TODO Auto-generated method stub
						mPaths.add(path);
						mAdapter.notifyDataSetChanged();
					}
				});
				break;
			case 800:
				boolean b = data.getBooleanExtra(KEY_DATA, false);
				if (b) {
					showToast("登陆成功，现在可以分享了");
				}
				break;
			}

		}
	}

	class GridAdapter extends ListBaseAdapter<String> {

		public GridAdapter(Context context, List<String> list) {
			super(context, list);
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			int count = super.getCount();
			return count == 9 ? count : count + 1;// 最多8张图片
		}

		@Override
		public View initView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			SquareImageView iv = new SquareImageView(ShareActivity.this);
			iv.setScaleType(ScaleType.FIT_XY);
			if (position < getCount() - 1 || mPaths.size() == 9) {
				AppContext.displayLocalImg(iv, getItem(position));
			} else {
				iv.setImageResource(R.drawable.ic_add_plus);
			}

			return iv;
		}

	}

	@Override
	public void onUpload(long current, long total, long progress) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onUploadSuccess(String data) {
		// TODO Auto-generated method stub
		if (mIndex < mPaths.size()) {
			// JSONObject json = new JSONObject(data);
			// if (json.has("Data")) {
			// String url = json.getString("Data");
			mStringBuilder.append(data);
			if (mIndex != mPaths.size() - 1) {
				mStringBuilder.append(";");
			}
			// }
			uploadImgs(mIndex + 1);
		}
	}

	@Override
	public void onUploadError(String error) {
		// TODO Auto-generated method stub
		cancelProgressDialog();
		showToast(R.string.upload_error);
	}

}
